package com.ruoyi.common.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.ruoyi.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class WxMiniProgramUtils {

    // 微信小程序 获取
    public static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

    public static final String GET_MINI_PROGRAM_QR_CODE_URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s";

    @Value("${wx.appId}")
    private String MINI_PROGRAM_APP_ID;

    @Value("${wx.secret}")
    private String MINI_PROGRAM_APP_SECRET;


    /**
     * 生成小程序分享二维码
     *
     * @param jumpUrl
     * @param scene
     * @param envVersion
     * @return
     */
    public byte[] generateMiniProgramQrCode(String jumpUrl, String scene, String envVersion) {
        String accessToken = getMiniProgramAccessToken();
        ByteArrayOutputStream bos = null;
        try {
            //调用微信接口生成二维码
            String qrCodeUrl = String.format(GET_MINI_PROGRAM_QR_CODE_URL, accessToken);
            URL url = new URL(qrCodeUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());

            // 包装请求参数
            // 可参考微信小程序接口文档地址 https://developers.weixin.qq.com/minigame/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html
            JSONObject paramJson = new JSONObject();
            paramJson.put("scene", scene);
            paramJson.put("page", jumpUrl);
            paramJson.put("width", 200);
            paramJson.put("is_hyaline", true);
            paramJson.put("auto_color", true);
            paramJson.put("check_path", false);
            paramJson.put("env_version", envVersion);
            printWriter.write(paramJson.toString());

            printWriter.flush();
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            bos = new ByteArrayOutputStream();
            int len;
            byte[] arr = new byte[8192];

            StringBuilder result = new StringBuilder();
            while ((len = bis.read(arr)) != -1) {
                bos.write(arr, 0, len);
                result.append(new String(arr));
                bos.flush();
            }
            bis.close();
            return bos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    public com.alibaba.fastjson2.JSONObject getEncryptPhone(String code) {
        Map<String, Object> param = new HashMap<>();
        param.put("appid", MINI_PROGRAM_APP_ID);
        param.put("secret", MINI_PROGRAM_APP_SECRET);
        param.put("js_code", code);
        param.put("grant_type", "authorization_code");
        String result = HttpUtil.get("https://api.weixin.qq.com/sns/jscode2session", param);
        log.info("请求用户手机号返回报文-----{}", result);
        com.alibaba.fastjson2.JSONObject jb = com.alibaba.fastjson2.JSON.parseObject(result);
        return jb;
    }


    public com.alibaba.fastjson2.JSONObject decryptPhone(String encryptedData, String sessionKey, String iv) {
        log.info("encryptedData:{},sessionKey:{},iv:{}", encryptedData, sessionKey, iv);
        //被加密的数据
        byte[] dataByte = Base64.getDecoder().decode(encryptedData);
        //加密秘钥
        byte[] keyByte = Base64.getDecoder().decode(sessionKey);
        //偏移量
        byte[] ivByte = Base64.getDecoder().decode(iv);
        try {
            //如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            //初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            //初始化
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, StandardCharsets.UTF_8);
                return com.alibaba.fastjson2.JSON.parseObject(result);
            }
        } catch (Exception e) {
            log.error("解密，获取微信信息错误", e);
        }
        throw new ServiceException();
    }


    public String getMiniProgramAccessToken() {
        String tokenUrl = String.format(GET_ACCESS_TOKEN_URL, MINI_PROGRAM_APP_ID, MINI_PROGRAM_APP_SECRET);
        ResponseEntity<String> tokenExchange = new RestTemplate().exchange(tokenUrl, HttpMethod.GET, null, String.class);
        Map<String, Object> resultMap = JSON.parseObject(tokenExchange.getBody(), new TypeReference<Map<String, Object>>() {
        });
        try {
            String accessToken = resultMap.get("access_token").toString();
            return accessToken;
        } catch (Exception exception) {
            throw new RuntimeException("获取小程序accessToken失败！");
        }
    }


//    byte[] bytes = wxMiniProgramService.generateMiniProgramQrCode("pages/entry/index", "scene", "release");
//        try {
//        BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes));
//        ImageIO.write(image, "png", new File("D:\\桌面\\qrCode.png"));
//    } catch (Exception e) {
//        throw new RuntimeException("图片生成失败！");
//    }
}
